--EventCenter
--[[
	观察者模式：（行为型）
	事件系统
--]]

require 'Class'

--事件类型（Enum）
EventType = {
	Player_Lv_Up_1 = 1,
	Player_Kill_Count_Add_1 = 2,
	Ping_out = 3,
	NUM = 4,
}

EventCenter = Singleton:GetInstance()  --事件中心（单例）
EventCenter.containner = {}  --容器
EventCenter.Subscribe = function(self,eventType,callback)  --注册
	if not self.containner[eventType] then
		local callbackArray = {}
		callbackArray[1] = callback
		self.containner[eventType] = callbackArray
	else
		table.insert(self.containner[eventType],callback)
	end
end
EventCenter.Unsubscribe = function(self,eventType,callback)  --注销
	if not self.containner[eventType] then return end
	for k,v in pairs(self.containner[eventType]) do
		if v == callback then
			self.containner[eventType][k] = nil
		end
	end
end
EventCenter.Fire = function(self,eventType,...)  --发送事件
	if not self.containner[eventType] then return end
	for k,v in pairs(self.containner[eventType]) do
		v(...)
	end
end

--------Main--------
PlayerModule = Class()  --玩家模块

PlayerModule.Init = function(self)
	EventCenter:GetInstance():Subscribe(EventType.Player_Lv_Up_1,self.Cb)
end
PlayerModule.Cb = function(times)
	print(string.format('玩家升级了：%d次',times))
end
PlayerModule.BeforeDestory = function(self)
	EventCenter:GetInstance():Unsubscribe(EventType.Player_Lv_Up_1,self.Cb)  --注销事件
end

BattleModule = Class()  --战斗模块
BattleModule.Init = function(self)
	local kill_enemy_cb = function(nums)
		print(string.format('玩家击败了%d个敌人',nums))
	end
	EventCenter:GetInstance():Subscribe(EventType.Player_Kill_Count_Add_1,kill_enemy_cb)
	local cb = function(times)
		print(string.format('战斗让玩家升级了：%d次',times))
	end
	EventCenter:GetInstance():Subscribe(EventType.Player_Lv_Up_1,cb)
end

function main()
	playerModule = PlayerModule:New()
	playerModule:Init()
	battleModule = BattleModule:New()
	battleModule:Init()
	EventCenter:GetInstance():Fire(EventType.Player_Lv_Up_1,5)  --玩家升级了：5次
																--战斗让玩家升级了：5次
	EventCenter:GetInstance():Fire(EventType.Player_Kill_Count_Add_1,10)  --玩家击败了10个敌人

	playerModule:BeforeDestory()  --注销事件
	EventCenter:GetInstance():Fire(EventType.Player_Lv_Up_1,5)  --战斗让玩家升级了：5次
end

main()
